package org.budo.support.web.realserverport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public class RealServerPortRequestWrapper extends HttpServletRequestWrapper {
    private String[] realServerPortHeaderNames;

    public RealServerPortRequestWrapper(HttpServletRequest request, String[] realServerPortHeaderNames) {
        super(request);
        this.setRealServerPortHeaderNames(realServerPortHeaderNames);
    }

    @Override
    public int getServerPort() {
        int serverPort = this.getServerPort(this);
        return serverPort > 0 ? serverPort : super.getServerPort();
    }

    private int getServerPort(HttpServletRequest request) {
        for (String headerName : this.getRealServerPortHeaderNames()) {
            String serverPort = request.getHeader(headerName);
            if (serverPort != null && !serverPort.isEmpty()) {
                return Integer.parseInt(serverPort);
            }
        }

        return 0;
    }
    
    @Override
    public String toString() {
        return super.toString() + ", wrapped(" + this.getRequest() + ")";
    }
}